/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jfDiscoWindows.java
 *
 * Created on 22/10/2011, 15:31:17
 */
package visao;

import agent.AgentMBean;
import com.sun.java.swing.plaf.windows.resources.windows;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import mbeanserver.MBServer;
import util.Computer;

/**
 *
 * @author alan
 */
public class jfDiscoWindows extends javax.swing.JFrame {

    MBeanServerConnection JMXSC;
    DefaultListModel modeloLista = new DefaultListModel();
    MBServer mbServer;
    private ObjectName windows;

    public jfDiscoWindows(MBServer mbServer) {
        try {
            initComponents();
            this.setLocationRelativeTo(this);
            this.mbServer = mbServer;
            JMXSC = mbServer.getMBServer();
            windows = new ObjectName("tcc:type=MACHINEWINDOWS");

        } catch (Exception ex) {
        }
    }

    public void buscaComputer() {
        try {
            String ip;
            String nome;
            Set<ObjectInstance> listaObject = JMXSC.queryMBeans(new ObjectName("tcc:*"), null);
            for (ObjectInstance objectInstance : listaObject) {
                if (objectInstance.getObjectName().getKeyProperty("type").equals("MACHINEWINDOWS")) {
                    ip = objectInstance.getObjectName().getKeyProperty("ip");
                    nome = objectInstance.getObjectName().getKeyProperty("nome");
                    Computer computer = new Computer(ip, nome, "");
                    verificaEspLivre(computer);
                }
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Não foi possível realizar a busca. Talvez não exista computadores ligados na rede");
        }
    }

    public void verificaEspLivre(Computer computer) {
        Double definicao = new Double(jtfDiscoEspLivre.getText());
        MBeanServerConnection jmx = AgentMBean.makeAgent(computer.getIp());
        try {
            String cUnidade = null;
            String cValor = null;
            int contUnid = 1;
            int contValor = 3;
            int contInterno = 1;
            String letra = (String) jmx.getAttribute(windows, "VolumeUnidDisco");
            for (StringTokenizer stringTokenizer = new StringTokenizer(letra); stringTokenizer.hasMoreTokens();) {
                String token = stringTokenizer.nextToken();
                if (contInterno == contUnid) {
                    cUnidade = token;
                    contUnid += 4;
                }
                if (contInterno == contValor) {
                    cValor = token;
                    contValor += 4;
                    Double valor = new Double(cValor.replace(',', '.'));
                    DecimalFormat df = new DecimalFormat("###");
                    String format = df.format(valor);
                    valor = new Double(format);
                    if (!modeloLista.contains(computer)) {
                        if (valor <= definicao) {
                            modeloLista.addElement(computer);
                        }
                    }
                }
                contInterno++;
            }
        } catch (MBeanException ex) {
            Logger.getLogger(jfDiscoWindows.class.getName()).log(Level.SEVERE, null, ex);
        } catch (AttributeNotFoundException ex) {
            Logger.getLogger(jfDiscoWindows.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstanceNotFoundException ex) {
            Logger.getLogger(jfDiscoWindows.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ReflectionException ex) {
            Logger.getLogger(jfDiscoWindows.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(jfDiscoWindows.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpPc = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jlPCDiscoLivre = new javax.swing.JList();
        jpLivre = new javax.swing.JPanel();
        jbBuscaDisco = new javax.swing.JButton();
        jtfDiscoEspLivre = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jpPc.setBorder(javax.swing.BorderFactory.createTitledBorder("Computadores"));

        jlPCDiscoLivre.setModel(modeloLista);
        jScrollPane1.setViewportView(jlPCDiscoLivre);

        javax.swing.GroupLayout jpPcLayout = new javax.swing.GroupLayout(jpPc);
        jpPc.setLayout(jpPcLayout);
        jpPcLayout.setHorizontalGroup(
            jpPcLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpPcLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
                .addContainerGap())
        );
        jpPcLayout.setVerticalGroup(
            jpPcLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpPcLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)
                .addContainerGap())
        );

        jpLivre.setBorder(javax.swing.BorderFactory.createTitledBorder("Definição de  espaço livre em disco (GB)"));

        jbBuscaDisco.setText("Buscar");
        jbBuscaDisco.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbBuscaDiscoActionPerformed(evt);
            }
        });

        jtfDiscoEspLivre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfDiscoEspLivreActionPerformed(evt);
            }
        });

        jLabel1.setText("Quantidade em GB");

        javax.swing.GroupLayout jpLivreLayout = new javax.swing.GroupLayout(jpLivre);
        jpLivre.setLayout(jpLivreLayout);
        jpLivreLayout.setHorizontalGroup(
            jpLivreLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpLivreLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jtfDiscoEspLivre, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 119, Short.MAX_VALUE)
                .addComponent(jbBuscaDisco)
                .addContainerGap())
        );
        jpLivreLayout.setVerticalGroup(
            jpLivreLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpLivreLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(jtfDiscoEspLivre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jbBuscaDisco))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpLivre, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jpPc, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jpLivre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jpPc, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jtfDiscoEspLivreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfDiscoEspLivreActionPerformed
}//GEN-LAST:event_jtfDiscoEspLivreActionPerformed

private void jbBuscaDiscoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbBuscaDiscoActionPerformed

    modeloLista.removeAllElements();
    jlPCDiscoLivre.validate();

    try {
        if (!"".equals(jtfDiscoEspLivre.getText())) {
            Double aDouble = new Double(jtfDiscoEspLivre.getText());
            buscaComputer();
        } else {
            JOptionPane.showMessageDialog(this, "Informe um número em GB para a busca");
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Informe apenas números");
    }

}//GEN-LAST:event_jbBuscaDiscoActionPerformed
    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(jfDiscoWindows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(jfDiscoWindows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(jfDiscoWindows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(jfDiscoWindows.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                new jfDiscoWindows().setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbBuscaDisco;
    private javax.swing.JList jlPCDiscoLivre;
    private javax.swing.JPanel jpLivre;
    private javax.swing.JPanel jpPc;
    private javax.swing.JTextField jtfDiscoEspLivre;
    // End of variables declaration//GEN-END:variables
}
